<?php
namespace Martdb\Libs;

/** Custom class/interface */
/**
 * Thin Util contains binary encoded/decoded methods
 *
 * @author Chunlin Jing
 */
class ThinUtil
{
  /**
   * Copy src array to dest array
   */
  public static function arraycopy(&$src, $srcPos, &$dest, $destPos, $length) {
    for ($i = 0; $i < $length; $i++) {
      $dest[$destPos++] = $src[$srcPos++];
    }
  }

  /**
   * Convert to signed byte
   */
  public static function toByte($value) {
    return $value > 127 ? $value - 256 : $value;
  }

  // Output unsigned byte array() string(Thrift binary type)
  public static function array2String($bytes) {
    $str = '';
    for ($i = 0, $j = count($bytes); $i < $j; $i++) {
      $b = $bytes[$i];
      $b = $b < 0 ? $b + 256 : $b;
      $str .= chr($b);
    }
    return $str;
  }

  private static $le = null;
  public static function isLittleEndian() {
    if (is_null(self::$le)) {
      self::$le = self::_isLittleEndian();
    }
    return self::$le;
  }

  private static function _isLittleEndian() {
    $t = 0x00FF;
    $p = pack('S', $t);
    return $t === current(unpack('v', $p));
  }
}
?>